package com.atguigu.myjuc2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket{
    private int ticket=60;
//    public synchronized void sale(){
//        if(ticket>0){
//            System.out.println(Thread.currentThread().getName()+"卖了第:"+(ticket--)+"\t"+"还剩"+ticket);
//        }
//        try {
//            TimeUnit.MILLISECONDS.sleep(200);
//        } catch (InterruptedException e) {
//           e.printStackTrace();
//        }
//    }
    private  final Lock lock=new ReentrantLock();
    public void sale(){
        lock.lock();
        try {
            if(ticket>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+(ticket--)+"\t"+"还剩"+ticket);
            }
        } finally {
         lock.unlock();
        }
    }
}
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
//         new Thread(new Runnable() {
//             @Override
//             public void run() {
//                 for (int i = 0; i < 60; i++) {
//                     ticket.sale();
//                 }
//             }
//         }, "张三").start();
//
//         new Thread(new Runnable() {
//             @Override
//             public void run() {
//                 for (int i = 0; i < 60; i++) {
//                     ticket.sale();
//                 }
//             }
//         }, "李四").start();
//
//         new Thread(new Runnable() {
//             @Override
//             public void run() {
//                 for (int i = 0; i < 60; i++) {
//                     ticket.sale();
//                 }
//             }
//         }, "王五").start();

        new Thread(()-> {for (int i = 0; i < 60; i++) ticket.sale();}, "王五").start();
        new Thread(()-> {for (int i = 0; i < 60; i++) ticket.sale();}, "李四").start();
        new Thread(()-> {for (int i = 0; i < 60; i++) ticket.sale();}, "张三").start();
    }
}
